import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../style/app_colors.dart';

class BarChartSample2 extends StatefulWidget {
  const BarChartSample2({super.key});

  final Color leftBarColor = AppColors.contentColorYellow;
  final Color rightBarColor = AppColors.contentColorRed;
  final Color avgColor = AppColors.contentColorOrange;

  @override
  State<BarChartSample2> createState() => _BarChartSample2State();
}

class _BarChartSample2State extends State<BarChartSample2> {
  final double width = 4.w;

  late List<BarChartGroupData> rawBarGroups;
  late List<BarChartGroupData> showingBarGroups;

  int touchedGroupIndex = -1;

  @override
  void initState() {
    super.initState();
    rawBarGroups = List.generate(12, (i) {
      final y1 = [5, 16, 18, 20, 17, 19, 13, 16, 17, 21, 14, 15][i].toDouble();
      final y2 = [12, 12, 5, 16, 6, 15, 5, 19, 25, 15, 5, 19][i].toDouble();
      return makeGroupData(i, y1, y2);
    });
    showingBarGroups = List.of(rawBarGroups);
  }

  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;
    final tt = Theme.of(context).textTheme;

    return AspectRatio(
      aspectRatio: 1.1,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(8.h),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                makeTransactionsIcon(cs.primary),
                SizedBox(width: 16.w),
                Text('Transactions',
                    style: tt.titleMedium?.copyWith(color: cs.onSurface)),
                SizedBox(width: 4.w),
                Text('state',
                    style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
              ],
            ),
          ),
          SizedBox(height: 24.h),
          Expanded(
            child: BarChart(
              BarChartData(
                maxY: 20,
                barTouchData: BarTouchData(
                  touchTooltipData: BarTouchTooltipData(
                    getTooltipColor: (_) => cs.surfaceVariant,
                    getTooltipItem: (a, b, c, d) => null,
                  ),
                  touchCallback: (event, response) {
                    if (response == null || response.spot == null) {
                      _resetTouched();
                      return;
                    }
                    touchedGroupIndex = response.spot!.touchedBarGroupIndex;
                    if (!event.isInterestedForInteractions) {
                      _resetTouched();
                      return;
                    }
                    setState(() {
                      showingBarGroups = List.of(rawBarGroups);
                      if (touchedGroupIndex != -1) {
                        final rods =
                            showingBarGroups[touchedGroupIndex].barRods;
                        final avg =
                            rods.map((e) => e.toY).reduce((a, b) => a + b) /
                                rods.length;
                        showingBarGroups[touchedGroupIndex] =
                            showingBarGroups[touchedGroupIndex].copyWith(
                          barRods: rods
                              .map((rod) => rod.copyWith(
                                  toY: avg, color: widget.avgColor))
                              .toList(),
                        );
                      }
                    });
                  },
                ),
                titlesData: FlTitlesData(
                  show: true,
                  rightTitles: const AxisTitles(
                      sideTitles: SideTitles(showTitles: false)),
                  topTitles: const AxisTitles(
                      sideTitles: SideTitles(showTitles: false)),
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      getTitlesWidget: bottomTitles,
                      reservedSize: 38.h,
                    ),
                  ),
                  leftTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      reservedSize: 32.w,
                      interval: 1,
                      getTitlesWidget: leftTitles,
                    ),
                  ),
                ),
                borderData: FlBorderData(show: false),
                barGroups: showingBarGroups,
                gridData: const FlGridData(show: false),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _resetTouched() {
    setState(() {
      touchedGroupIndex = -1;
      showingBarGroups = List.of(rawBarGroups);
    });
  }

  Widget leftTitles(double value, TitleMeta meta) {
    final labels = {0: '1K', 10: '5K', 20: '10K', 30: '15K'};
    final label = labels[value.toInt()];
    if (label == null) return const SizedBox.shrink();
    return SideTitleWidget(
      axisSide: meta.axisSide,
      space: 0,
      child: Text(label,
          style: Theme.of(context).textTheme.bodySmall?.copyWith(
                fontWeight: FontWeight.bold,
              )),
    );
  }

  Widget bottomTitles(double value, TitleMeta meta) {
    const titles = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec'
    ];
    return SideTitleWidget(
      axisSide: meta.axisSide,
      space: 6.h,
      child: Text(
        titles[value.toInt()],
        style: Theme.of(context).textTheme.bodySmall?.copyWith(
              fontWeight: FontWeight.bold,
          fontSize: 10.sp
            ),
      ),
    );
  }

  BarChartGroupData makeGroupData(int x, double y1, double y2) {
    return BarChartGroupData(
      barsSpace: 4.w,
      x: x,
      barRods: [
        BarChartRodData(toY: y1, color: widget.leftBarColor, width: width),
        BarChartRodData(toY: y2, color: widget.rightBarColor, width: width),
      ],
    );
  }

  Widget makeTransactionsIcon(Color baseColor) {
    const width = 4.5;
    const space = 3.5;
    final colors = [
      baseColor.withOpacity(0.4),
      baseColor.withOpacity(0.8),
      baseColor,
      baseColor.withOpacity(0.8),
      baseColor.withOpacity(0.4)
    ];
    final heights = [10.h, 28.h, 42.h, 28.h, 10.h];
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(colors.length, (i) {
        return Row(
          children: [
            Container(width: width.w, height: heights[i], color: colors[i]),
            if (i < colors.length - 1) SizedBox(width: space.w),
          ],
        );
      }),
    );
  }
}
